package com.dream.dao.impl;


import com.dream.dao.DepartmentDao;
import com.dream.pojo.Department;
import com.dream.utils.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class DepartmentDaoImpl implements DepartmentDao {

    @Override
    public long totalCount(String deptName) {
        String sql = "select count(department.dept_id) FROM department where 1=1";
        StringBuilder sb = new StringBuilder(sql);
        if(deptName!=null && !"".equals(deptName)){
            sb.append(" and department.dept_name like '%"+deptName+"%'");
        }
        return DBUtil.queryCount(sb.toString());
    }

    @Override
    public List<Department> list(String deptName, long pageIndex, long pageSize) {
        String sql = "select * FROM department where 1=1";

        StringBuilder sb = new StringBuilder(sql);
        if(deptName!=null && !"".equals(deptName)){
            sb.append(" and department.dept_name like '%"+deptName+"%'");
        }
        sb.append(" limit ?,?");
        return DBUtil.commonQuery(Department.class, sb.toString(),(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public int add(Department department) {
        try {
            DBUtil.commonUpdate("insert into department values (?,?,?)",
                    department.getDeptId(),
                    department.getDeptName(),
                    department.getRemark());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Department findById(String deptId) {
        ArrayList<Department> list = DBUtil.commonQuery(Department.class, "select * from department where dept_id=?", deptId);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    @Override
    public int update(Department department) {
        try {
            DBUtil.commonUpdate("update department set dept_name=?,remark=? where dept_id=?",
                    department.getDeptName(),
                    department.getRemark(),department.getDeptId());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteById(String deptId) {
        try {
            DBUtil.commonUpdate("delete from  department where dept_id=?", deptId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Department> getAllDept() {
        return  DBUtil.commonQuery(Department.class, "select * from department");
    }
}
